package com.Adapter;

import java.util.List;
import java.util.concurrent.ExecutionException;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.CustomClasses.FetchImage;
import com.bolao.R;
import com.entidades.News;

public class NewsAdapter extends BaseAdapter {

	private List<News> news;
	private LayoutInflater mInflater;
	
	static class ViewHolder{
		TextView title;
		ImageView image;
		TextView desc;
		ProgressBar pbar;
	}
	
	public NewsAdapter(Context context, List<News> news){
		mInflater = LayoutInflater.from(context);
		this.news = news;
	}
	
	@Override
	public int getCount() {
		return news.size();
	}

	@Override
	public News getItem(int id) {
		return news.get(id);
	}

	@Override
	public long getItemId(int id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.news_layout, null);
			
			holder = new ViewHolder();

			holder.image = (ImageView) convertView.findViewById(R.id.imageViewNewsImage);
			holder.title = (TextView) convertView.findViewById(R.id.textViewNewsTitle);
			holder.pbar = (ProgressBar) convertView.findViewById(R.id.progressBarNews);
			convertView.setTag(holder);
			
		}else{
			holder = (ViewHolder) convertView.getTag();
			holder.image.setImageResource(android.R.color.transparent);
		}

		News mNew = news.get(position);
		holder.title.setText(mNew.getmTtitle());
		if(mNew.getImage()!=null){
		holder.image.setImageBitmap(mNew.getImage());
		} else {

		try {
			holder.image.setImageBitmap(new FetchImage(holder.pbar).execute(mNew).get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		}
		return convertView;
	}
}
